import logging

import webapp2
from google.appengine.api import users
from util.webapp import ShopkeepApplication, ShopkeepHandler
from models.Message import Message
from models.Item import Item
from models.User import User

class MessagePage(ShopkeepHandler):
	def get(self):
		user = users.get_current_user()

		if self.thread_id == "":
			data = []
			for m in Message.get_unique_conversations(user, True, False):
				data.append(m)

			self.render_response("user_inbox.html", {"messages": data, "recipient": self.request.get('recipient')})
		else:
			query = Message.getThread(self.thread_id)
			data = {"messages": query.run(), "user": user}
			self.render_response("user_message_display.html", data)

	# post is used to send replys
	def post(self):
		user = users.get_current_user()

		content = self.request.POST.get('message', '')
		recipient_id = self.request.POST.get('recipient', '')
		item_id = self.request.POST.get('item', 0)

		# If a thread ID is specified, load info from the
		# thread. Otherwise, it's a new thread.
		if self.thread_id:
			query = Message.getThread(self.thread_id)
			m = query.get()
			# security check here
			if m.sender != user and m.recipient != user:
				self.abort(403)
			m.reply(content, user)
			logging.info('User replied to message.', extra={'target': m.sender})
			self.get()
		else:
			if item_id:
				item = Item.get_by_id(int(item_id))
				if item is None:
					self.abort(400)
			else:
				item = None

			recipient = User.get_by_id(int(recipient_id))
			if recipient is None:
				self.abort(400)

			# Make new thread and redirect to it.
			message = Message(recipient=recipient.id, item=item, content=content)
			message.put()
			logging.info('User sent message.', extra={'target': recipient.id})
			self.redirect(self.request.url + '/' + str(message.thread_id))

	@webapp2.cached_property
	def thread_id(self):
		info = self.request.path.split('/')
		assert info[0] == ''

		if len(info) == 3:
			return info[2]
		else:
			return ""
		
app = ShopkeepApplication([('/messages(?:/.*)?', MessagePage)])
